<template>
  <codemirror
    class="xml-code-mirror"
    ref="myCm"
    v-model="codeStr"
    :options="cmOptions"
    @input="onCmCodeChange"
  ></codemirror>
</template>

<script>
import { codemirror } from "vue-codemirror";
import "codemirror/mode/sql/sql";
import "codemirror/addon/fold/foldcode.js";
import "codemirror/addon/fold/foldgutter.js";
import "codemirror/addon/fold/brace-fold.js";
import "codemirror/addon/fold/comment-fold.js";

import "codemirror/lib/codemirror.css";
import "codemirror/mode/css/css";
import "codemirror/addon/fold/foldgutter.css";

import "codemirror/mode/css/css";
import "codemirror/theme/base16-light.css";
import "codemirror/addon/selection/active-line";

export default {
  name: "SqlCodeMirror",
  components: {
    codemirror
  },
  props: {
    code: {
      type: String,
      default: ""
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    lineNumbers: {
      type: Boolean,
      default: true
    }
  },
  model: {
    prop: "code",
    event: "change"
  },
  data() {
    return {
      codeStr: "",
      cmOptions: {
        // codemirror options
        tabSize: 2,
        mode: "text/x-sql",
        readOnly: this.readOnly,
        theme: "base16-light",
        lineNumbers: this.lineNumbers,
        line: true,
        indentWithTabs: true,
        lineWrapping: true,
        foldGutter: true,
        gutters: [
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter",
          "CodeMirror-lint-markers"
        ],
        showCursorWhenSelecting: true,
        spellcheck: true,
        lineWrapping: true
      }
    };
  },
  watch: {
    code: {
      immediate: true,
      handler(val) {
        this.codeStr = val;
      }
    }
  },
  methods: {
    onCmCodeChange(newCode) {
      this.$emit("change", newCode);
    }
  }
};
</script>
<style lang="less">
.xml-code-mirror {
  line-height: 24px;
}
</style>
